﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AiXiu.IDAL;
using AiXiu.Common;
using AiXiu.Model;
using System.Data.Entity;

namespace AiXiu.DAL
{
    public class VideoDAL : IVideoDAL
    {
        AiXiuDbContext db = new AiXiuDbContext();
        public int addVideo(TBVideos video)
        {
            video.UploadTime = GetSqlMethod.getMsServerDateTime();

            db.Entry(video).State = EntityState.Added;
            return db.SaveChanges();
        }

        #region 同步更新视频状态
        public List<string> GetVideosIdByState()
        {
            return db.TBVideos.Where(t => 
                t.Status ==(int)VideoStatus.Uploading ||
                t.Status == (int)VideoStatus.UploadSucces ||
                t.Status == (int)VideoStatus.Transcoding
            ).Select(t => t.VideoId).ToList();
        }

        public int UpdateVideosState(List<VideoInfo> newTBVideos)
        {
            int saveChangesCount = 0;
            foreach (VideoInfo item in newTBVideos)
            {
                TBVideos video = db.TBVideos.FirstOrDefault(t => t.VideoId == item.VideoId);
                string coveUrl = item.CoverURL;
                if (!string.IsNullOrWhiteSpace(coveUrl))
                {
                    coveUrl = coveUrl.Substring(0, coveUrl.LastIndexOf('?'));
                }
                video.CoverURL = coveUrl;
                video.Status = Convert.ToInt32(item.Status);
                db.Entry(video).State = EntityState.Modified;
            }
            db.SaveChanges();
            return saveChangesCount;
        }
        #endregion



        public List<TBVideos> GetVideosList()
        {
            return db.TBVideos.Where(t => t.Status == (int)VideoStatus.Normal).ToList();
        }

        public TBVideos GetVideoById(string videoId)
        {
            return db.TBVideos.First(t => t.VideoId == videoId);
        }

        public List<TBVideos> GetTBVideosByUserId(int userId)
        {
            return db.TBVideos.Where(t => t.UserId == userId).OrderByDescending(t => t.UploadTime).ToList();
        }

        public int DeleteVideoById(string videoId)
        {
            TBVideos video = db.TBVideos.First(t => t.VideoId == videoId);

            db.Entry(video).State = EntityState.Deleted;
            return db.SaveChanges();
        }
    }
}
